<?php

namespace app\api\controller;

use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use app\api\model\Schedule;
use app\common\controller\Api;
use think\Request;

/**
 * 支付接口
 */
class Payment extends Api
{
    protected $noNeedLogin = ['money_notify', 'gold_coin_notify'];
    protected $noNeedRight = ['*'];

    const alipay_public_key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyhOT5+cZt+o4X42SoWofJoYTpDQPFVZ3ssTYfDjWnT2epg/vjRmofy7tB7FnkyiMDGXBBp1QIl3y6H+dMFGdJN6abUDgtvtXdXZazVymiW/kUKOqBbT+98O9Nr9O2joonVXe7u3b+af6nsyw2yeGDQiCle889Jjp84T8NcPHOxQ47L7qNsbjS3MASUHp38g5WlSzU/31tgf/C2XCi9CBbMqDR3X5kXZiF4J7ObmNOVporCPHizvW20WmAiizt2K4bn9aRdATf3jMA49e06Y2BdrKunySuBMCIrK8g9/WShMvduc78hykUZ9VmbkcZs5aazuV8TW/SHUr3kqH1Wag7wIDAQAB';

    /**
     * 支付宝接口
     */
    public function aliPayInterface()
    {
        vendor('aop/AopClient');
        vendor('aop/request/AlipayTradeAppPayRequest');
        $aop = new \AopClient;
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = "2021002113624007";
        $aop->rsaPrivateKey = 'MIIEowIBAAKCAQEAiJ5lGRHTpvOR5qZyP1k5iVfpLj3cI+clqQ/SbhkESPbOau9fhROBGanXvpphYcyX/HC6ShI+IpLQMuqFPmzH8OUHLDPojFe7ct4FIAsgWOGhnlQaVlY/Jn6h2q7y45X21MDjKGAAuPUA9kv0iUs32kAL7XI6IoUDe8DRZTc+l52wRRGe7W3ppsCiasSC534Tk4O9BePAhrB6PYNqbnVJOBeYRGlDv5k6SzQ+TWmXqS1pwKskYjy8hHFlb9GC4Kw2oE1ryG+uzhx3DEM+Cc+hydBmffeIQ3cm6pEQi3w4+YsBqD0B4rGcBzIB9kfwWT3kFbPJXvbkgdSreqsXK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tM4PgUoS7Bj938Gz65aj1mA/2olDPMkV1jXdRso7ej3rtW6ulCB6kiBXnB4YBWwHR+xLsdG2alPRYAKEhGkLXZqRyypOLAVX9eemGUrHgT2/Lru/B3zs1fv5hjpBwpWKhv6giNXhYkhr07Leqbyqih16Q2ll90RG';
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = self::alipay_public_key;
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \AlipayTradeAppPayRequest();
        $shop_name = input('name');
//        $price = input('price');
        $price = 0.01;
        $type = input('type');
        $order_number = rand() . '_' . $this->uid;
        if ($type == 1) {
            //充值余额回调地址
            $request->setNotifyUrl(config('href_url') . "/api/payment/money_notify");
        } else {
            //充值金币回调地址
            $request->setNotifyUrl(config('href_url') . "/api/payment/gold_coin_notify");
        }
//SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizContent = "{"
            . "\"subject\": \"" . $shop_name . "\","
            . "\"out_trade_no\": \"" . $order_number . "\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"" . $price . "\""
            . "}";
        $request->setBizContent($bizContent);
//这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        $data = htmlspecialchars($response);
        $data = str_replace('amp;', '', $data);
        $this->success('成功', ['data' => $data]);
    }

    //获取数据
    public function getData()
    {
        $data = $_POST;
        vendor('aop/AopClient');
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = self::alipay_public_key;
        $flag = $aop->rsaCheckV1($data, NULL, "RSA2");

        $data['flag'] = $flag;
        return $data;
    }

    //充值余额回调
    public function gold_coin_notify()
    {
        $data = $this->getData();
        //商户订单号
        $order_id = $data['out_trade_no'];
        //交易状态
        $trade_status = $data['trade_status'];
        //查看是否存在该未支付订单，下面可以根据自己业务逻辑编写
        $order = explode('_', $order_id);
        foreach ($order as $v) {
            $result = model('user')->where(['id' => $order[1]])->find();//获取用户信息
            //存在该用户并支付成功，进行修改
            if ($result && $trade_status == "TRADE_SUCCESS") {
                $result->money += $data['total_amount'];//修改余额
                $result->save();
                return 'success';
            }
        }
    }

    //充值金币回调
    public function money_notify()
    {
        $data = $this->getData();
        //商户订单号
        $order_id = $data['out_trade_no'];
        //交易状态
        $trade_status = $data['trade_status'];
        //查看是否存在该未支付订单，下面可以根据自己业务逻辑编写
        $order = explode('_', $order_id);
        foreach ($order as $v) {
            $result = model('user')->where(['id' => $order[1]])->find();//获取用户信息
            //存在该用户并支付成功，进行修改
            if ($result && $trade_status == "TRADE_SUCCESS") {
                $exchange = db('configuration')->value('exchange');//获取兑换比例
                $result->gold_coin += $data['total_amount'] * (float)$exchange;//修改金币余额
                $result->save();
                return 'success';
            }
        }
    }

    /**
     * 订单退款
     */
    public function orderReturn()
    {
        vendor('aop/AopClient');
        vendor('aop/request/AlipayTradeRefundRequest');
        $aop = new \AopClient ();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = "2021002113624007";
        $aop->rsaPrivateKey = 'MIIEowIBAAKCAQEAiJ5lGRHTpvOR5qZyP1k5iVfpLj3cI+clqQ/SbhkESPbOau9fhROBGanXvpphYcyX/HC6ShI+IpLQMuqFPmzH8OUHLDPojFe7ct4FIAsgWOGhnlQaVlY/Jn6h2q7y45X21MDjKGAAuPUA9kv0iUs32kAL7XI6IoUDe8DRZTc+l52wRRGe7W3ppsCiasSC534Tk4O9BePAhrB6PYNqbnVJOBeYRGlDv5k6SzQ+TWmXqS1pwKskYjy8hHFlb9GC4Kw2oE1ryG+uzhx3DEM+Cc+hydBmffeIQ3cm6pEQi3w4+YsBqD0B4rGcBzIB9kfwWT3kFbPJXvbkgdSreqsXK7I94QIDAQABAoIBAGkVNHwA+0R6Kuo3cr8JOTlMFj6MNEylWZFdayVmNqaMuB8GeflZFD8SJbEk++yGuwzgBFo/B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RyypOLAVX9eemGUrHgT2/Lru/B3zs1fv5hjpBwpWKhv6giNXhYkhr07Leqbyqih16Q2ll90RG';
        $aop->signType = "RSA2";
        $aop->apiVersion = '1.0';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $request = new \AlipayTradeRefundRequest ();
        $out_request_no = randNumber() . rand(1, 100);
        $alipay_trade_no = input('alipay_trade_no');
        $price = input('price');
        $request->setBizContent("{" .
            "\"trade_no\":\"" . $alipay_trade_no . "\"," .//支付宝交易号
//            "\"out_trade_no\":\"".$alipay_trade_no."\"," .//商家订单号
            "\"refund_amount\":" . $price . "," .
            "\"out_request_no\":" . $out_request_no . "," .
            "\"refund_reason\":\"正常退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if ($resultCode == '10000') {
            \app\api\model\Order::update(['status' => 3], ['alipay_trade_no' => $alipay_trade_no]);
            $this->success('退款成功');
        } else {
            $this->error('退款失败');
        }
    }
}
